module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage6.Stage6HomeGui".new()
local wEasing = require "wEasing"

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view

-----------------------------------------------------------------------------
		
	local mainGroup, backgroundGroup, stageButtonGroup, homeButtonGroup, generateItemsGroup
	local bg,replayButton
	local scoreText
	local score,scoreMinus = 0,0
	local totalTimer,timerText,timer_countdownReady,_countDownTimerEachTurn,_delayTimerEachTurn = nil,nil,nil,nil,nil
	local totalTime,timeDelay, timeDelta = 20000,100,0
	local timeToTouch ,TIMETOTOUCH = 2,2
	local timeReady = 2
	local timeDelayEachTurn = 2
	local timerText,txtGo, timerTextReady
	local deltaTime = 4000
	
	local countDownTurn = 10
	local DELTA = 2
	local delta = DELTA
	local timeEachTurn = 30 * delta
	local dT = 1000 * delta
	local t, _tran
	
	local itemEachTurn = 3
	local foodCount
	
	local imageButtons, imageItems = {},{}
	local countDownItems = {0,0,0,0,0,0}
	
	local isTouchOk = true
	
	local timeStartTurn,timeStopTurn, time = 0,0
	
	local countTimes = 0
	
	local tFormer,pLater = 0,0
	local timeScore = {}
	local delayTimerEachTurn,countDownTimerEachTurn
	local generateItem
	local _gameOver,finishedGame
	
	local _scoreText = {}
	
	local okImage,goodImage,perfectImage

	
--------------------------- create group -------------------------------
	mainGroup = display.newGroup()
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
-----------------------------------
deltaTime = itemEachTurn * 500
	
------------------ helper function -----------------------

local exceptRandom = function(startNumber,endNumber,exceptNumber)
	local temp = {}
	local j = 0
	for i = 1,endNumber-startNumber+1,1 do
		j = j+1
		if(startNumber+i-1 ~= exceptNumber) then 
			temp[j] = startNumber + i -1
		else
			j = j - 1 
		end
	end
	_temp = math.random(1,endNumber - startNumber)
	return temp[_temp]
end

function checkWinTurn(countDownItems)
	local flag = true
	for k,v in pairs(countDownItems)do
		if(v ~= 0) then flag = false end
	end
	return flag
end

local function onStartGenerateItems()
	isTouchOk = false
end

local function onFinishGenerateItems()
	isTouchOk = true
	_delayTimerEachTurn = timer.performWithDelay(100,delayTimerEachTurn,0)
	tFormer = system.getTimer()
	timeStartTurn = system.getTimer()
	-- visible ok --
end

local function onReplayButtonTap()
	destroyAll()
end

function destroyAll()
	if(_delayTimerEachTurn ~= nil) then
		timer.cancel(_delayTimerEachTurn)
	end
	if(_countDownTimerEachTurn ~= nil) then
		timer.cancel(_countDownTimerEachTurn)
	end
	if(timer_countdownReady ~=nil)then
		timer.cancel(timer_countdownReady)
	end
	timeToTouch = TIMETOTOUCH
	itemEachTurn = 3
	if(_tran ~= nil) then
		transition.cancel(_tran)
	end
	for k,v in pairs(imageItems) do
		display.remove(v)
	end
	if(_gameOver ~= nil) then
		display.remove(_gameOver)
	end
	txtGo.alpha = 0
	timerText.alpha = 0
	timeDelayEachTurn = 2
	timeReady = 2
	countTimes = 0
	timerTextReady.text = timeReady
	timerTextReady.alpha = 1
	timer_countdownReady = timer.performWithDelay(1000,countdownReady,0)
end

----------------------- handler function -------------------------	
function runtimeHandle()
	
end

function checkResultEachTurn(_time)
	----------------------- show result image ---------------------
		if(_time >0 and _time <= 1000)then
			perfectImage.alpha = 1
			okImage.alpha = 0
			goodImage.alpha = 0
		end
		if(_time >1000 and _time <= 2000)then
			goodImage.alpha = 1
			okImage.alpha = 0
			perfectImage.alpha = 0
		end
		if(_time >2000) then
			okImage.alpha = 1
			goodImage.alpha = 0
			perfectImage.alpha = 0
		end
	------------ delay --------------
	
end

function countdownReady ()
	timerTextReady.alpha = 1
	timeReady = timeReady - 1
	timerTextReady.text = timeReady
	if timeReady <0 then
		timerTextReady.alpha = 0
		txtGo.alpha = 1
	end
	if timeReady <-1 then
		timeReady = 2
		isTouchOk = true
		txtGo.alpha = 0
		timer.cancel(timer_countdownReady)
		generateItem(itemEachTurn)
		countTimes = countTimes + 1
		-- t = system.getTimer()
	end
end

function delayTimerEachTurn()
	timeDelayEachTurn = timeDelayEachTurn - 0.2
	txtGo.text = "Touch"
	if(txtGo.alpha == 0) then 
		txtGo.alpha = 1
	else
		txtGo.alpha = 0
	end
	
	if( timeDelayEachTurn < 0 )then
		txtGo.alpha = 0
		timer.cancel(_delayTimerEachTurn)
		-- t = system.getTimer()
		timeDelayEachTurn = 2
		_countDownTimerEachTurn = timer.performWithDelay(100, countDownTimerEachTurn, 0)
	end
end

function countDownTimerEachTurn()
	timeToTouch = timeToTouch - 0.1
	timerText.text = math.round(10*timeToTouch)/10
	timerText.alpha = 1
	if( timeToTouch < 0 ) then
		timeToTouch = TIMETOTOUCH
		if(checkWinTurn(countDownItems)) then
			timeScore[countTimes] = system.getTimer() - tFormer
			checkResultEachTurn(timeScore[countTimes])
			-- timer_countdown = timer.performWithDelay(100,countdownTime,0)
			score = score + 1
			scoreText.text = score
		else
			gameOver()
			return
		end
		isTouchOk = true
		timer.cancel(_countDownTimerEachTurn)
		if(itemEachTurn < 6 )then
			itemEachTurn = itemEachTurn + 1
		end
		if(countTimes < 10) then
			generateItem(itemEachTurn)
			countTimes = countTimes + 1
		else
			finishedGame()
		end
	end
	
end

function countdownTime (event)
	--------------------------------
	-- generateItem(itemEachTurn)
	-- t = system.getTimer()
	--------------------------
	
	
	timerText.alpha = 1
	if( deltaTime < (system.getTimer() - t)) then
		timerText.text = "0"
		timer.cancel(timer_countdown)
		_delayTimerEachTurn = timer.performWithDelay(200,delayTimerEachTurn,0)
	end
	
	timerText.text = (math.round((deltaTime - tonumber((system.getTimer() - t)))/100))/10 ..""
	for i = 1,3 do
		-- arrayButton[i]:addEventListener("tap", countClick)
	end
end


function onMoveButtonTap(event)
	local t = event.target
	if(isTouchOk == false) then
		for k,v in pairs(imageButtons) do
			v:removeEventListener("tap",onMoveButtonTap)
		end
		gameOver()
		return
	end
	
	countDownItems[tonumber(t.id)] = countDownItems[tonumber(t.id)] - 1
	
	print(t.id," = ",countDownItems[tonumber(t.id)])
	
	if(checkWinTurn(countDownItems)) then
		timeScore[countTimes] = system.getTimer() - tFormer
		
		checkResultEachTurn(timeScore[countTimes])
		
		if(_delayTimerEachTurn ~= nil) then
			timer.cancel(_delayTimerEachTurn)
		end
		if(_countDownTimerEachTurn ~= nil) then
			timer.cancel(_countDownTimerEachTurn)
		end
		timeDelayEachTurn = 2
		timeToTouch = TIMETOTOUCH
		
		score = score +1
		scoreText.text = score
		countTimes = countTimes + 1
		if(itemEachTurn < 10)then
			itemEachTurn = itemEachTurn + 1
			generateItem(itemEachTurn)
		else
			finishedGame()
		end
		return
	end
	
	if(countDownItems[tonumber(t.id)] < 0) then
		for k,v in pairs(imageButtons) do
			v:removeEventListener("tap",onMoveButtonTap)
		end
		gameOver()
	end
	scoreText.text = score .."PTS"
end

function finishedGame()
	print("victory")
end

function gameOver()
	txtGo.alpha = 0
	if(_tran ~= nil) then
		transition.cancel(_tran)
	end
	_gameOver = display.newText(mainGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	_gameOver.x = display.contentCenterX
	_gameOver.y = display.contentCenterY
	_gameOver:setTextColor(unpack(gui.score.color))
	_gameOver.alpha = 1
	if(_delayTimerEachTurn ~= nil) then
		timer.cancel(_delayTimerEachTurn)
	end
	if(_countDownTimerEachTurn ~= nil) then
		timer.cancel(_countDownTimerEachTurn)
	end
	if(timer_countdownReady ~=nil)then
		timer.cancel(timer_countdownReady)
	end
	for k,v in pairs(timeScore) do
		print(v)
	end
	return _gameOver
end

function generateItem(itemEachTurn)
	local id
	local temp1Position,temp2Position,tempPosition
	
	for k,v in pairs(imageButtons)do
		v:removeEventListener("tap",onMoveButtonTap)
	end
	timerText.alpha = 0
	local backgroundButton = {}
	backgroundButton[1] = display.newImageRect(stageButtonGroup,gui.leftButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
		backgroundButton[1].x = gui.buttonPosition.x[1]
		backgroundButton[1].y = gui.buttonPosition.y[1]
	backgroundButton[2] = display.newImageRect(stageButtonGroup,gui.centerButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
		backgroundButton[2].x = gui.buttonPosition.x[2]
		backgroundButton[2].y = gui.buttonPosition.y[2]
	backgroundButton[3] = display.newImageRect(stageButtonGroup,gui.rightButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
		backgroundButton[3].x = gui.buttonPosition.x[3]
		backgroundButton[3].y = gui.buttonPosition.y[3]
	
	temp1Position = math.random(1,6)
	imageItems[1] = display.newImageRect(generateItemsGroup, gui.image[temp1Position].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[1].x = 1*gui.displayWidth/4
		imageItems[1].y = 265
		imageItems[1].id = temp1Position
		
	imageButtons[1] = display.newImageRect(stageButtonGroup,gui.image[temp1Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[1].x = gui.buttonPosition.x[1]
		imageButtons[1].y = gui.buttonPosition.y[1]
		imageButtons[1].id = temp1Position
		imageButtons[1]:addEventListener("tap",onMoveButtonTap)
	
	temp2Position = exceptRandom(1,6,temp1Position)
	imageItems[2] = display.newImageRect(generateItemsGroup, gui.image[temp2Position].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[2].x = 2*gui.displayWidth/4
		imageItems[2].y = 265
		imageItems[2].id = temp2Position
	
	
	imageButtons[2] = display.newImageRect(stageButtonGroup,gui.image[temp2Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[2].x = gui.buttonPosition.x[2]
		imageButtons[2].y = gui.buttonPosition.y[2]
		imageButtons[2].id = temp2Position
		imageButtons[2]:addEventListener("tap",onMoveButtonTap)
	
	local temp3Position = 1
	while (temp3Position == temp1Position or temp3Position == temp2Position) do
		temp3Position = math.random(1,6)
	end
	imageButtons[3] = display.newImageRect(stageButtonGroup,gui.image[temp3Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[3].x = gui.buttonPosition.x[3]
		imageButtons[3].y = gui.buttonPosition.y[3]
		imageButtons[3].id = temp3Position
		imageButtons[3]:addEventListener("tap",onMoveButtonTap)
	
	for i = 3,itemEachTurn,1 do
		tempPosition = math.random(1,6)
		imageItems[i] = display.newImageRect(generateItemsGroup, gui.image[tempPosition].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[i].x = i*gui.displayWidth/4
		imageItems[i].y = 265
		imageItems[i].id = tempPosition
	end
	
	---------- count  items each category ---------------
	local i
	for i=1,6,1 do
		countDownItems[i] = 0
	end
	for k,v in pairs(imageButtons) do
		for k1,v1 in pairs(imageItems) do
			if (v.id == v1.id) then
				countDownItems[tonumber(v.id)] = countDownItems[tonumber(v.id)] + 1
			end
		end
	end
	-- for i = 1,6,1 do
		-- print(countDownItems[i])
	-- end
	for k,v in pairs(_scoreText) do
		display.remove(v)
	end
	for k,v in pairs(imageButtons)do
		_scoreText[k] = display.newText(countDownItems[tonumber(v.id)],v.x+50, v.y - 50,native.systemFontBold,18)
		_scoreText[k]:setTextColor(255,0,0)
	end
	
	generateItemsGroup.x =  -1 * (itemEachTurn /4) *gui.displayWidth
	_tran = transition.to(generateItemsGroup,{time = itemEachTurn * 2000, alpha = 1, x = gui.displayWidth, y = generateItemsGroup.y, onStart = onStartGenerateItems, onComplete = onFinishGenerateItems })
end
------------------------------- score -------------------
scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
homeButtonGroup:insert(scoreText)

-------------------- background and button ---------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})
	
leftButton = display.newImageRect(stageButtonGroup, gui.leftButton.fn, gui.leftButton.w, gui.leftButton.h)
	leftButton.x = gui.leftButton.x
	leftButton.y = gui.leftButton.y
	leftButton.id = "left"
	leftButton.isVisible = false
leftButton:addEventListener("tap", onMoveButtonTap)

centerButton = display.newImageRect(stageButtonGroup, gui.centerButton.fn, gui.centerButton.w, gui.centerButton.h)
	centerButton.x = gui.centerButton.x
	centerButton.y = gui.centerButton.y
	centerButton.id = "center"
	centerButton.isVisible = false
centerButton:addEventListener("tap",onMoveButtonTap)
	
rightButton = display.newImageRect(stageButtonGroup, gui.rightButton.fn, gui.rightButton.w, gui.rightButton.h)
	rightButton.x = gui.rightButton.x
	rightButton.y = gui.rightButton.y
	rightButton.id = "right"
	rightButton.isVisible = false
rightButton:addEventListener("tap", onMoveButtonTap)

okImage = display.newImageRect(homeButtonGroup,gui.okImage.fn,gui.okImage.w,gui.okImage.h)
	okImage.x = gui.okImage.x
	okImage.y = gui.okImage.y
	okImage.alpha = 0

goodImage = display.newImageRect(homeButtonGroup,gui.goodImage.fn,gui.goodImage.w,gui.goodImage.h)
	goodImage.x = gui.goodImage.x
	goodImage.y = gui.goodImage.y
	goodImage.alpha = 0

perfectImage = display.newImageRect(homeButtonGroup,gui.perfectImage.fn,gui.perfectImage.w,gui.perfectImage.h)
	perfectImage.x = gui.perfectImage.x
	perfectImage.y = gui.perfectImage.y
	perfectImage.alpha = 0
	
mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(homeButtonGroup)

------------------------------------ text -----------------
timerText = display.newText(mainGroup, deltaTime/1000, gui.timer.x, gui.timer.y, native.systemFont, gui.timer.fontSize)
	timerText:setTextColor(255,0,0)
	timerText.alpha = 0
	
timerTextReady = display.newText(mainGroup, timeReady,160 , 150, gui.timer.font, gui.timer.fontSize+20)
	timerTextReady:setTextColor(255,0,0)
	timerTextReady.alpha = 1
  
txtGo = display.newText(mainGroup, "GO", 160 -30, 150, gui.timer.font, gui.timer.fontSize+20)
	txtGo:setTextColor(255,0,0)
	txtGo.alpha = 0

------------------------------------- run test --------------------------------------


----------------------------- end run test ------------------------------------------------
-- totalTimer = timer.performWithDelay( timeDelay, manageTotalTime, 0 )
timer_countdownReady = timer.performWithDelay(1000,countdownReady,0)


-- Runtime:addEventListener("enterFrame", runtimeHandle)
end




-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local group = self.view
	-- local prior_scene = storyboard.getPrevious()
	-- if (prior_scene)then
		-- storyboard.purgeScene( prior_scene )
	-- end
	
	-----------------------------------------------------------------------------
		
	--	INSERT code here (e.g. start timers, load audio, start listeners, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene